package com.market.xg.gateway.event;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class DynamicRouteEvent implements ApplicationEventPublisherAware {

    @Autowired
    RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationEventPublisher eventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        log.info("setApplicationEventPublisher");
        this.eventPublisher = applicationEventPublisher;
    }

    public void addRoute(RouteDefinition routeDefinition){
        try {
            routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
            this.eventPublisher.publishEvent(new RefreshRoutesEvent(this));
        }catch (Exception e){
            log.error("addRouteError",e);
        }

    }
    public void updateRoute(RouteDefinition routeDefinition){
        try {
            routeDefinitionWriter.delete(Mono.just(routeDefinition.getId()));
        }catch (Exception e){
          log.error("deleteRouteError",e);
        }
        this.addRoute(routeDefinition);
    }
}
